<?php

namespace App\Admin\Controllers\Auth;

use App\Admin\Controllers\Controller;
use App\Admin\Services\AuthService;
use App\Admin\Services\GrantService;
use App\Admin\Traits\RouteHelper;

class RoleController extends Controller
{
    use RouteHelper;

    protected $grantService;
    protected $authService;

    public function __construct()
    {
        parent::__construct();
        $this->grantService = new GrantService();
        $this->authService  = new AuthService();
    }

    /**
     * 角色列表
     */
    public function index()
    {
        $limit = request()->get('limit') ?? 30;
        $roles = $this->grantService->getRoles('', $limit);
        $items = $this->grantService->setPermissionsToRole($roles->items());

        if (request()->ajax()) {
            return $this->laytable($roles->total(), $items);
        }

        return view('admin.role.index', ['roles' => $roles]);
    }

    /**
     * 添加角色-前台
     */
    public function create()
    {
        //獲取所有權限提供前台選擇
        $permissions = $this->grantService->getPermissions();
        return view('admin.role.create', ['permissions' => $permissions]);
    }

    /**
     * 添加角色-後台
     */
    public function store()
    {
        $roleName    = request()->get('roleName');
        $permissions = request()->get('permissions')[0] ?? '';

        try {
            // 添加角色
            $role = $this->grantService->createRoles($roleName);
            // 添加權限
            if (isset($permissions)) {
                $permissions = explode(',', $permissions);
                $role->givePermissionTo($this->grantService->getPermissionIn($permissions));
            }
            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 修改角色
     */
    public function edit()
    {
        $role = $this->grantService->getRoles(request()->id);
        //獲取用戶的所有權限
        $allPermissions = $this->grantService->getPermissions();
        $permissions    = $role->permissions;
        $ownPermission  = [];
        foreach ($permissions as $permission) {
            $ownPermission[] = $permission->name;
        }
        return view('admin.role.edit', [
            'role'          => $role,
            'permissions'   => $allPermissions,
            'ownPermission' => $ownPermission,
        ]);
    }

    /**
     * 保存角色修改
     */
    public function update()
    {
        $roleId      = request()->get('roleId');
        $roleName    = request()->get('roleName');
        $permissions = request()->get('permissions')[0] ?? '';

        try {
            // 更新角色名
            $this->grantService->updateRoles($roleName, $roleId);
            $role = $this->grantService->getRoles($roleId);
            // 修改角色權限
            if (isset($permissions)) {
                $permissions = (array)explode(',', $permissions);
                $role->syncPermissions($this->grantService->getPermissionIn($permissions));
            }
            return $this->success('操作成功');
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 刪除角色
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws
     */
    public function delete()
    {
        $id = request('id');

        if (empty($id)) {
            return $this->failure('未選擇', [], 200);
        }

        try {
            if ($this->grantService->deleteRoles($id)) {
                return $this->success('刪除成功');
            }
        } catch (\Exception $e) {
            $this->failure($e->getMessage());
        }
    }

    /**
     * 對角色添加授權
     */
    public function assignRolePermission()
    {
        $id           = request()->get('roleId');
        $permissionId = request()->get('permissionId');
        $role         = $this->grantService->getRole($id);
        $permission   = $this->grantService->getPermission($permissionId);

        if ($role->givePermissionTo($permission->name)) {
            return $this->success('操作成功');
        }

        return $this->failure('操作失敗');
    }

    public function export()
    {
        // 查出所有用戶角色及權限
        $roles = $this->grantService->getRoles("", 100);
        $ckey  = 67;

        foreach ($roles->items() as $key => $role) {
            $heads[$key]['cell_id']                = chr($ckey) . "1";
            $heads[$key]['name']                   = $role->name;
            $role_cells[chr($ckey)]['id']          = $role->id;
            $role_cells[chr($ckey)]['permissions'] = $this->getRolePermission($role->id);
            $ckey++;
        }

        // 所有權限
        $all_routes    = $this->getRoutes();
        $format_routes = [];

        foreach ($all_routes as $route) {
            $description                      = explode(":", $route['description']);
            $route['description']             = $description[1] ?? $description[0];
            $format_routes[$description[0]][] = $route;
        }

        return Excel::create('角色权限', function ($excel) use ($heads, $format_routes, $role_cells) {
            $excel->sheet('角色权限', function ($sheet) use ($heads, $format_routes, $role_cells) {
                // 表頭
                $sheet->cell("A1", function ($cell) {
                    $cell->setValue("類別");
                });
                $sheet->cell("B1", function ($cell) {
                    $cell->setValue("權限");
                });
                foreach ($heads as $head) {
                    $sheet->cell($head['cell_id'], function ($cell) use ($head) {
                        $cell->setValue($head['name']);
                    });
                }
                // 數據
                if (!empty($format_routes)) {
                    $cell_i = 0;
                    foreach ($format_routes as $key => $format_route) {
                        if (!empty($format_route)) {
                            foreach ($format_route as $k => $v) {
                                $i = $cell_i + 2;
                                $sheet->cell("A" . $i, $key);
                                $sheet->cell("B" . $i, $v['description']);
                                foreach ($role_cells as $chr => $role_cell) {
                                    $sheet->cell($chr . $i, function ($cell) use ($role_cell, $v) {
                                        if (in_array($v['path'], $role_cell['permissions'])) {
                                            $cell->setValue("√");
                                        } else {
                                            $cell->setValue("");
                                        }
                                    });
                                }
                                $cell_i++;
                            }
                        }
                    }
                }
            });
        })->download('xlsx');
    }

    public function getRolePermission($role_id)
    {
        $role        = $this->grantService->getRoles($role_id);
        $permissions = $role->permissions;
        $permissions = array_column($permissions->toArray(), 'route');
        $permissions = implode(",", $permissions);

        return explode(",", $permissions);
    }
}
